package com.dx.mes.service.special.service;
/**
 * Created by admin on 2017/6/30.
 */
import com.dx.common.table.ppt.*;
import com.dx.mes.common.dao.IBisOpeDao;
import com.dx.mes.common.dao.IBisPathiDao;
import com.dx.mes.common.dao.IRetPrdInfoDao;
import com.dx.mes.common.table.rtnBean.NotFoundRtnBeen;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.special.service.IFspgrdchgService;
import com.dx.mes.facade.special.tx.Fspgrdchg.FspgrdchgI;
import com.dx.mes.facade.special.tx.Fspgrdchg.FspgrdchgIA;
import com.dx.mes.facade.special.tx.Fspgrdchg.FspgrdchgO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.dx.mes.common.bean.def.GenericDef.*;


@Service("fspgrdchgService")
public class FspgrdchgService implements IFspgrdchgService  {
    private static final String TX_NAME = T_FSPGRDCHG;
    private LogUtils logUtils;

    @Autowired
    private IRetPrdInfoDao retPrdInfoDao;
    @Autowired
    private IBisPathiDao bisPathiDao;
    @Autowired
    private IBisOpeDao bisOpeDao;
    @Override
    public String subMainProc(String evt_no, String strInTrx) {
        AppContext.clear();
        AppContext.setCurrServiceName(FspgrdchgService.class.getSimpleName());
        AppContext.setCurrEventNumber(evt_no);
        logUtils = new LogUtils(FspgrdchgService.class);
        logUtils.info("[InTrx:" + strInTrx + "]");
        String strOutTrx = "";
        FspgrdchgI inTrx = new FspgrdchgI();
        FspgrdchgO outTrx = new FspgrdchgO();
        outTrx.setTrx_id(TX_NAME);
        outTrx.setType_id(TRX_OUT);
        outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));

        try {
            inTrx = JacksonUtil.fromJson(strInTrx, FspgrdchgI.class);
            char action_flg = inTrx.getAction_flg().charAt(0);
            switch (action_flg) {
                case 'U':
                    updateFnc(inTrx, outTrx);
                    break;
                default:
                    errActionFnc(outTrx);
            }
            if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
                retPrdInfoDao.flushCurSession();
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } catch (Exception ex) {
            outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
            outTrx.setRtn_mesg(ex.toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            strOutTrx = JacksonUtil.toJSONStr(outTrx);
            logUtils.info("[OutTrx:" + strOutTrx + "]");
        }
        return strOutTrx;
    }


    public void updateFnc(FspgrdchgI inTrx,FspgrdchgO outTrx) {
        List<FspgrdchgIA> iary = inTrx.getIary();
        String rsnCate = iary.get(0).getRsn_cate();
        String rsnCode = iary.get(0).getRsn_code();
        String rsnDept = iary.get(0).getRsn_dept();
        String evtUsr  = iary.get(0).getEvtUsr();
        List<Ret_prd_info>  retPrdInfos = iary.get(0).getRet_prd_info();
        Timestamp evt_timestamp = Util.getCurrentTimestamp();
        for(Ret_prd_info prd :retPrdInfos){
            String prd_grade = prd.getPrd_grade();
      /*      String chip_grade = prd.getChip_grade();*/
            Ret_prd_info ret_prd_info = retPrdInfoDao.get(prd.getPrd_seq_id());
            if (!ret_prd_info.getPrd_stat().equals(PROC_IN_PROCESS) && !ret_prd_info.getPrd_stat().equals(PROC_WAIT)) {
                outTrx.setRtn_code(E_FSPGRDCHG_STATUS_MISMATCH + "");
                outTrx.setRtn_mesg("玻璃状态不正确，必须为[WAIT]");
                return;
            }
            Bis_pathi bis_pathi = new Bis_pathi();
            Bis_pathiId id = new Bis_pathiId();
            Bis_ope bis_ope = new Bis_ope();
            Bis_opeId ope_key = new Bis_opeId();
            if(ret_prd_info.getPrd_stat().equals(PROC_IN_PROCESS) ){
                ope_key.setOpe_id(ret_prd_info.getCr_ope_id_fk());
                ope_key.setOpe_ver(ret_prd_info.getCr_ope_ver_fk());

                id.setPath_id(ret_prd_info.getCr_path_id_fk());
                id.setPath_ver(ret_prd_info.getCr_path_ver_fk());
            }else if(ret_prd_info.getPrd_stat().equals(PROC_WAIT)){
                ope_key.setOpe_id(ret_prd_info.getNx_ope_id_fk());
                ope_key.setOpe_ver(ret_prd_info.getNx_ope_ver_fk());

                id.setPath_id(ret_prd_info.getNx_path_id_fk());
                id.setPath_ver(ret_prd_info.getNx_path_ver_fk());
            }
            //check 玻璃所在的站点是不是INS或者PACK
         /*   bis_ope = bisOpeDao.get(ope_key);
            if (null == bis_ope) {
                outTrx.setRtn_code(E_BIS_OPE + E_READ_NOT_FOUND + "");
                outTrx.setRtn_mesg(new NotFoundRtnBeen(ret_prd_info.getCr_ope_id_fk(), Bis_ope.class).toString());
                return;
            }*/
            /**
             * INS站之后才可以更改等级
             */
          /*  if(!bis_ope.getTool_run_mode().trim().equals(TOOL_RUN_MODE_INS) && !bis_ope.getTool_run_mode().trim().equals(TOOL_RUN_MODE_PACK)){
                outTrx.setRtn_code(E_FSPGRDCHG_TOOL_RUN_MODE_MISMATCH + "");
                outTrx.setRtn_mesg("玻璃["+ret_prd_info.getPrd_seq_id()+"]必须在INS站之后才可以更改等级，请确认！");
                return;
            }*/

            //check 玻璃是不是在主工艺路线上
            bis_pathi = bisPathiDao.get(id);
            if(!bis_pathi.getPath_cate().equals(PATH_TYPE_MAIN)){
                outTrx.setRtn_code(E_FSPGRDCHG_PATH_CATE_MISMATCH + "");
                outTrx.setRtn_mesg("玻璃["+ret_prd_info.getPrd_seq_id()+"]不在主工艺路线上，请确认！");
                return;
            }

            Ret_prd_info retPrdInfo = retPrdInfoDao.get(ret_prd_info.getPrd_seq_id());
            retPrdInfo.setPrd_grade(prd_grade);
       /*   retPrdInfo.setChip_grade(chip_grade);*/
            retPrdInfo.setEvt_cate(EVT_UPDATEGRADE);
            retPrdInfo.setRsn_code(rsnCode);
            retPrdInfo.setRsn_dept(rsnDept);
            retPrdInfo.setRsn_cate(rsnCate);
            retPrdInfo.setEvt_usr(evtUsr);
            retPrdInfo.setExt_9(prd.getExt_9());
            retPrdInfo.setEvt_timestamp(evt_timestamp);
            retPrdInfoDao.update(retPrdInfo);
        }

        /**
         * CHECK 混等
         */
      /*  Set<String> boxIdSet = new HashSet<String>();
        retPrdInfos.forEach(ret_prd_info -> boxIdSet.add(ret_prd_info.getBox_id_fk()));
        for (String box_id:boxIdSet) {
            List<Ret_prd_info> retPrdInfoList = retPrdInfoDao.getShtListInfo(box_id);
            String prd_grade = retPrdInfoList.get(0).getPrd_grade();
            List<String> grades = retPrdInfoList.stream().map(ret_prd_info -> ret_prd_info.getPrd_grade()).collect(Collectors.toList());
            List<String> repeatGrade = grades.stream().filter(s -> !s.equals(prd_grade)).collect(Collectors.toList());
            if(!repeatGrade.isEmpty()){
                outTrx.setRtn_code(E_FSPGRDCHG_PRD_GRADE_MIX + "");
                outTrx.setRtn_mesg("箱子["+box_id+"]内玻璃的等级不一样！");
                return;
            }
        }*/

        outTrx.setRtn_code(RETURN_CODE_OK);
        outTrx.setRtn_mesg(RETURN_MESG_OK);
    }
    public void errActionFnc(FspgrdchgO outTrx) {
        outTrx.setRtn_code("0000009");
        outTrx.setRtn_mesg("Invalid Action_flg");
    }
}
